import { loginAPI, getUserInfoAPI, getUserDetailByIdApi } from '@/api/user'
import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: null,
    userInfo: null,
    hrsaasTime: 0
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    removeToken(state) {
      state.token = null
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = null
    },
    setHrsaasTime(state, time) {
      state.hrsaasTime = time
    }
  },
  actions: {
    async loginAction({ commit }, data) {
      const res = await loginAPI(data)
      // console.log(res)
      commit('setToken', res)
      commit('setHrsaasTime', Date.now())
    },
    async getUserInfoAction({ commit }) {
      console.log('getUserInfoAPI', getUserInfoAPI)

      const res = await getUserInfoAPI()
      const baseRes = await getUserDetailByIdApi(res.userId)
      // console.log(res)
      commit('setUserInfo', { ...res, ...baseRes })
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
      resetRouter()
    }
  }
}

